﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Controller;
using Entity;

namespace Web
{
    public partial class EditUserInfo : System.Web.UI.Page
    {
        Helper helper = new Helper();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UserEntity userEntity = Session["User"] as UserEntity;
                if(userEntity!=null)
                {
                    UserNameLabel.Text = userEntity.UserName;
                    FullNameTextBox.Text = userEntity.FullName;
                    EmailTextBox.Text = userEntity.Email;    
                }
                else
                {
                    Session["FlashMessage"] = "Error: No Such User Information Matchs!";
                    Session["FlashMessageType"] = "error";
                }
            }

            this.PreRender += new EventHandler(UpdateFlashMessage);
        }

        private void UpdateFlashMessage(object sender, EventArgs e)
        {
            helper.ShowFlashMessage(FlashMessageLabel);
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            
            string userName = UserNameLabel.Text.ToUpper();
            string oldPassword = OldPwTextBox.Text.Trim();
            string enOldPw=FormsAuthentication.HashPasswordForStoringInConfigFile(oldPassword, "MD5");
            string newPw = FormsAuthentication.HashPasswordForStoringInConfigFile(NewPwTextBox.Text.Trim(), "MD5");
            UserController userController=new UserController();
            int comparePw = userController.CheckLogin(userName, enOldPw);
            if(comparePw==1) // old password passed.
            {
                UserEntity userEntity = new UserEntity();
                userEntity.UserName = userName;
                userEntity.Password = newPw;
                userEntity.FullName = FullNameTextBox.Text.Trim();
                userEntity.Email = EmailTextBox.Text.Trim();
                userController.UpdateUser(userEntity);
                Session["FlashMessage"] = "Success: Update Successful!";
                Session["FlashMessageType"] = "success";
            }
            if(comparePw==0) //old password wrong!
            {
                Session["FlashMessage"] = "Error: Old Password Is Wrong!";
                Session["FlashMessageType"] = "success";
            }
        }
    }
}